import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import { Button } from '@kernelproxy/ui';
import { useLanguage, useLocalizedLink } from '@kernelproxy/i18n';
import { authService } from '../services/auth';
import { Github, Mail, User, Lock, Eye, EyeOff } from 'lucide-react';
import LoadingBar from '../components/LoadingBar';

const Register = () => {
  const [email, setEmail] = useState('');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [step, setStep] = useState<'form' | 'success'>('form');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const { t, language } = useLanguage();
  const { getLink } = useLocalizedLink();
  const navigate = useNavigate();

  // Password strength validation
  const getPasswordStrength = (pass: string) => {
    if (pass.length === 0) return { strength: 0, label: '' };
    if (pass.length < 8) return { strength: 1, label: language === 'zh-CN' ? '太弱' : 'Too Weak' };
    
    let strength = 1;
    if (/[a-z]/.test(pass)) strength++;
    if (/[A-Z]/.test(pass)) strength++;
    if (/[0-9]/.test(pass)) strength++;
    if (/[^a-zA-Z0-9]/.test(pass)) strength++;
    
    if (strength <= 2) return { strength: 2, label: language === 'zh-CN' ? '弱' : 'Weak' };
    if (strength <= 3) return { strength: 3, label: language === 'zh-CN' ? '中等' : 'Medium' };
    return { strength: 4, label: language === 'zh-CN' ? '强' : 'Strong' };
  };

  const passwordStrength = getPasswordStrength(password);

  // Register with email and password
  const handleRegister = async (e: React.FormEvent) => {
    e.preventDefault();
    setError('');
    setLoading(true);

    // Validate passwords match
    if (password !== confirmPassword) {
      setError(language === 'zh-CN' ? '两次输入的密码不一致' : 'Passwords do not match');
      setLoading(false);
      return;
    }

    // Validate password strength
    if (password.length < 8) {
      setError(language === 'zh-CN' ? '密码至少需要8个字符' : 'Password must be at least 8 characters');
      setLoading(false);
      return;
    }

    try {
      const result = await authService.registerWithEmailPassword(
        email,
        password,
        username || undefined
      );

      if (result.success) {
        setStep('success');
      }
    } catch (err: any) {
      console.error('Registration error:', err);
      if (err.message?.includes('already exists') || err.message?.includes('user with the same email')) {
        setError(language === 'zh-CN' ? '该邮箱已被注册' : 'Email already registered');
      } else if (err.message?.includes('Invalid email')) {
        setError(language === 'zh-CN' ? '邮箱格式不正确' : 'Invalid email format');
      } else if (err.message?.includes('password')) {
        setError(language === 'zh-CN' ? '密码不符合要求，需至少8个字符' : 'Password must be at least 8 characters');
      } else {
        setError(err.message || (language === 'zh-CN' ? '注册失败，请重试' : 'Registration failed. Please try again.'));
      }
    } finally {
      setLoading(false);
    }
  };

  // Countdown timer for resend button

  const handleOAuthLogin = async (provider: 'google' | 'github') => {
    setError('');
    setLoading(true);
    
    try {
      await authService.oauthLogin(provider);
      // OAuth will redirect, so no need to handle success here
    } catch (err) {
      setError(language === 'zh-CN' ? '第三方登录失败' : 'OAuth login failed');
      setLoading(false);
    }
  };

  return (
    <>
      <LoadingBar loading={loading} />
      <div className="h-screen bg-gray-50 dark:bg-gray-900 flex items-center justify-center px-4 sm:px-6 lg:px-8 transition-colors duration-300">
        <div className="w-full max-w-md">
        <div className="text-center mb-8">
          <a href="https://kernelproxy.com" className="inline-flex items-center justify-center">
            <span className="text-3xl font-bold text-[#00d4ff]">kernel</span>
            <span className="text-3xl font-bold text-[#0f1c3f] dark:text-white">Proxy</span>
          </a>
          <h2 className="mt-6 text-3xl font-bold text-gray-900 dark:text-white">
            {t('register.title')}
          </h2>
          <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
            {t('register.or')}{' '}
            <Link to={getLink('/login')} className="font-medium text-[#00d4ff] hover:text-[#0f1c3f] dark:hover:text-[#00d4ff]/80">
              {t('register.loginLink')}
            </Link>
          </p>
        </div>
        
        <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow-lg sm:rounded-lg sm:px-10 transition-colors duration-300">
          {error && (
            <div className="mb-4 p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-md">
              <p className="text-sm text-red-600 dark:text-red-400">{error}</p>
            </div>
          )}

          {/* Registration Form */}
          {step === 'form' && (
            <form className="space-y-5" onSubmit={handleRegister}>
              <div>
                <label htmlFor="email" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  {language === 'zh-CN' ? '邮箱地址' : 'Email Address'}
                </label>
                <div className="mt-1 relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Mail className="h-5 w-5 text-gray-400" />
                  </div>
                  <input 
                    id="email" 
                    name="email" 
                    type="email" 
                    autoComplete="email" 
                    required 
                    value={email} 
                    onChange={e => setEmail(e.target.value)} 
                    placeholder={language === 'zh-CN' ? '输入您的邮箱' : 'Enter your email'}
                    className="appearance-none block w-full pl-10 px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300" 
                  />
                </div>
              </div>

              <div>
                <label htmlFor="username" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  {language === 'zh-CN' ? '用户名（可选）' : 'Username (Optional)'}
                </label>
                <div className="mt-1 relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <User className="h-5 w-5 text-gray-400" />
                  </div>
                  <input 
                    id="username" 
                    name="username" 
                    type="text" 
                    value={username} 
                    onChange={e => setUsername(e.target.value)} 
                    placeholder={language === 'zh-CN' ? '留空将自动生成 user-xxxxx' : 'Leave empty for auto user-xxxxx'}
                    className="appearance-none block w-full pl-10 px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300" 
                  />
                </div>
              </div>

              <div>
                <label htmlFor="password" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  {language === 'zh-CN' ? '密码' : 'Password'}
                </label>
                <div className="mt-1 relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Lock className="h-5 w-5 text-gray-400" />
                  </div>
                  <input 
                    id="password" 
                    name="password" 
                    type={showPassword ? 'text' : 'password'}
                    autoComplete="new-password" 
                    required 
                    value={password} 
                    onChange={e => setPassword(e.target.value)} 
                    placeholder={language === 'zh-CN' ? '至少8个字符' : 'At least 8 characters'}
                    className="appearance-none block w-full pl-10 pr-10 px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300" 
                  />
                  <button
                    type="button"
                    onClick={() => setShowPassword(!showPassword)}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center"
                  >
                    {showPassword ? (
                      <EyeOff className="h-5 w-5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" />
                    ) : (
                      <Eye className="h-5 w-5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" />
                    )}
                  </button>
                </div>
                {password && (
                  <div className="mt-2">
                    <div className="flex items-center gap-1">
                      {[1, 2, 3, 4].map(level => (
                        <div
                          key={level}
                          className={`h-1 flex-1 rounded-full transition-colors ${
                            level <= passwordStrength.strength
                              ? passwordStrength.strength === 1
                                ? 'bg-red-500'
                                : passwordStrength.strength === 2
                                ? 'bg-orange-500'
                                : passwordStrength.strength === 3
                                ? 'bg-yellow-500'
                                : 'bg-green-500'
                              : 'bg-gray-300 dark:bg-gray-600'
                          }`}
                        />
                      ))}
                    </div>
                    <p className="text-xs text-gray-500 dark:text-gray-400 mt-1">
                      {passwordStrength.label}
                    </p>
                  </div>
                )}
              </div>

              <div>
                <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700 dark:text-gray-300">
                  {language === 'zh-CN' ? '确认密码' : 'Confirm Password'}
                </label>
                <div className="mt-1 relative">
                  <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                    <Lock className="h-5 w-5 text-gray-400" />
                  </div>
                  <input 
                    id="confirmPassword" 
                    name="confirmPassword" 
                    type={showConfirmPassword ? 'text' : 'password'}
                    autoComplete="new-password" 
                    required 
                    value={confirmPassword} 
                    onChange={e => setConfirmPassword(e.target.value)} 
                    placeholder={language === 'zh-CN' ? '再次输入密码' : 'Re-enter password'}
                    className="appearance-none block w-full pl-10 pr-10 px-3 py-2 border border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white rounded-md shadow-sm placeholder-gray-400 dark:placeholder-gray-500 focus:outline-none focus:ring-[#00d4ff] focus:border-[#00d4ff] transition-colors duration-300" 
                  />
                  <button
                    type="button"
                    onClick={() => setShowConfirmPassword(!showConfirmPassword)}
                    className="absolute inset-y-0 right-0 pr-3 flex items-center"
                  >
                    {showConfirmPassword ? (
                      <EyeOff className="h-5 w-5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" />
                    ) : (
                      <Eye className="h-5 w-5 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300" />
                    )}
                  </button>
                </div>
              </div>

              <div className="flex items-center">
                <input 
                  id="terms" 
                  name="terms" 
                  type="checkbox" 
                  required 
                  className="h-4 w-4 text-[#00d4ff] focus:ring-[#00d4ff] border-gray-300 dark:border-gray-600 dark:bg-gray-700 rounded" 
                />
                <label htmlFor="terms" className="ml-2 block text-sm text-gray-900 dark:text-gray-300">
                  {language === 'zh-CN' ? '我同意' : 'I agree to the'}{' '}
                  <Link to={getLink('/terms-of-service')} className="text-[#00d4ff] hover:underline">
                    {language === 'zh-CN' ? '服务条款' : 'Terms of Service'}
                  </Link>{' '}
                  {language === 'zh-CN' ? '和' : 'and'}{' '}
                  <Link to={getLink('/privacy-policy')} className="text-[#00d4ff] hover:underline">
                    {language === 'zh-CN' ? '隐私政策' : 'Privacy Policy'}
                  </Link>
                </label>
              </div>

              <div>
                <Button type="submit" fullWidth variant="gradient" disabled={loading}>
                  {loading 
                    ? (language === 'zh-CN' ? '注册中...' : 'Registering...') 
                    : (language === 'zh-CN' ? '创建账户' : 'Create Account')}
                </Button>
              </div>
            </form>
          )}

          {/* Success Message */}
          {step === 'success' && (
            <div className="text-center space-y-4">
              <div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-green-100 dark:bg-green-900/20">
                <Mail className="w-8 h-8 text-green-600 dark:text-green-400" />
              </div>
              <div>
                <h3 className="text-lg font-semibold text-gray-900 dark:text-white mb-2">
                  {language === 'zh-CN' ? '验证邮件已发送' : 'Verification Email Sent'}
                </h3>
                <p className="text-sm text-gray-600 dark:text-gray-400 mb-4">
                  {language === 'zh-CN'
                    ? `我们已向 ${email} 发送了一封验证邮件。请检查您的收件箱并点击邮件中的链接以激活您的账户。`
                    : `We've sent a verification email to ${email}. Please check your inbox and click the link to activate your account.`}
                </p>
                <p className="text-xs text-gray-500 dark:text-gray-400">
                  {language === 'zh-CN'
                    ? '没收到邮件？请检查垃圾邮件文件夹，或者'
                    : "Didn't receive it? Check your spam folder, or "}
                  <Link to={getLink('/login')} className="text-[#00d4ff] hover:underline">
                    {language === 'zh-CN' ? '返回登录' : 'return to login'}
                  </Link>
                </p>
              </div>
            </div>
          )}

          {/* Divider */}
          <div className="relative my-6">
            <div className="absolute inset-0 flex items-center">
              <div className="w-full border-t border-gray-300 dark:border-gray-600"></div>
            </div>
            <div className="relative flex justify-center text-sm">
              <span className="px-2 bg-white dark:bg-gray-800 text-gray-500 dark:text-gray-400">
                {language === 'zh-CN' ? '或继续使用' : 'Or continue with'}
              </span>
            </div>
          </div>

          {/* OAuth Signup Buttons */}
          <div className="space-y-3">
            <button
              type="button"
              onClick={() => handleOAuthLogin('google')}
              disabled={loading}
              className="w-full flex items-center justify-center gap-3 px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm bg-white dark:bg-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-300"
            >
              <svg className="w-5 h-5" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
                <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
                <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
                <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
              </svg>
              {language === 'zh-CN' ? 'Google' : 'Google'}
            </button>

            <button
              type="button"
              onClick={() => handleOAuthLogin('github')}
              disabled={loading}
              className="w-full flex items-center justify-center gap-3 px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm bg-white dark:bg-gray-700 text-sm font-medium text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-300"
            >
              <Github className="w-5 h-5" />
              {language === 'zh-CN' ? 'GitHub' : 'GitHub'}
            </button>
          </div>
        </div>
      </div>
    </div>
    </>
  );
};

export default Register;
